package upload

import (
	"bytes"
	"dcs/db"
	"dcs/model"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strconv"
	"time"
)

type UploadMachineResult struct {
	Inserted_machine []int
}

type HttpResult struct {
	Jsonrpc string
	Id      uint32
	Result  string
}

type UpdateFields struct {
	Uploaded    int
	Upload_time string
}

var (
	Interval_upload_base_machine time.Duration
)

func init() {
	Interval_upload_base_machine = 3
}

func Upload_machines_2_wsc() {

	select_str := "tid, machine_no, machine_ip, spindle_count, spindle_mode, boot_delay"

	var mac model.Base_machine
	rows, _ := db.GormDb.Table("base_machine").Select(select_str).Where("uploaded != 1").Rows()
	//rows, _ := db.GormDb.Table("base_machine").Select(select_str).Rows()

	var machineStrArr []string
	for rows.Next() {
		db.GormDb.ScanRows(rows, &mac)
		machineStr := fmt.Sprintf("[%v, \"%v\", \"%v\", %v, %v, %v]", mac.Tid, mac.Machine_no,
			mac.Machine_ip, mac.Spindle_count, mac.Spindle_mode, mac.Boot_delay)
		machineStrArr = append(machineStrArr, machineStr)
	}

	// 如果没有新机台，则休眠1分钟
	if len(machineStrArr) < 1 {
		time.Sleep(time.Minute * 1)
		return
	}

	data := ""
	for i := 0; i < len(machineStrArr); i++ {
		if i == 0 {
			data += machineStrArr[i]
		} else {
			data += "," + machineStrArr[i]
		}
	}
	data = fmt.Sprintf("{\"factory_no\":\"%v\",\"machines\":[%v]}", Factory_no, data)
	jsonStr := []byte(data)
	url := Url + "AddMachineInfo" + "?db=" + Factory_no
	fmt.Println(data)

	httpClient := http.Client{Timeout: 5 * time.Second}
	resp, err := httpClient.Post(url, "application/json", bytes.NewBuffer(jsonStr))
	if err != nil {
		panic(err)
	}

	defer resp.Body.Close()
	result, _ := ioutil.ReadAll(resp.Body)
	fmt.Println(string(result))

	var httpResult HttpResult
	neterr := json.Unmarshal([]byte(result), &httpResult)
	if neterr != nil {
		panic(neterr)
	}

	var machines UploadMachineResult
	neterr = json.Unmarshal([]byte(httpResult.Result), &machines)
	if neterr != nil {
		panic(neterr)
	}

	Inserted_machines := ""
	for i := 0; i < len(machines.Inserted_machine); i++ {
		if i == 0 {
			Inserted_machines += strconv.Itoa(machines.Inserted_machine[i])
		} else {
			Inserted_machines += "," + strconv.Itoa(machines.Inserted_machine[i])
		}
	}

	if len(machines.Inserted_machine) > 0 {

		var updateData UpdateFields
		updateData.Uploaded = 1
		updateData.Upload_time = time.Now().Format("2006-01-02 15:04:05")

		db_obj := db.GormDb.Table("base_machine").Where("tid in (?)", machines.Inserted_machine)
		db_obj.Updates(&updateData)
	}

	// 每隔1分钟上传一次新机台数据
	time.Sleep(time.Second * 1)
}

func Cron_upload_base_machine() {

	for {
		Upload_machines_2_wsc()
		time.Sleep(time.Second * Interval_upload_base_machine)
	}

}
